package nl.dxn.tunnel.client.executors;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import nl.dxn.tunnel.CollectionUtils;
import nl.dxn.tunnel.client.Constants;
import nl.dxn.tunnel.po.TransferMessage;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class AuthExecutor {
    private static final Logger logger = LoggerFactory.getLogger(AuthExecutor.class);

    public static void execute(ChannelHandlerContext context, TransferMessage message) {
        if (StringUtils.isEmpty(message.getConfig().getResult())) {
            logger.info("隧道客户端注册成功，服务Id:{} 代理类型： {}", message.getConfig().getServerId(), message.getConfig().getProxyType());
            return;
        }

        logger.info("隧道客户端注册失败，服务Id:{} 密钥：{} 代理类型： {},失败原因：{}"
                , message.getConfig().getServerId()
                , message.getConfig().getServerKey()
                , message.getConfig().getProxyType()
                , message.getConfig().getResult());
        context.close();
        System.exit(-1);
    }

    public static void executeAgentDisConnect(ChannelHandlerContext context) {
        try {
            ConcurrentHashMap<String, Pair<EventLoopGroup, Channel>> map = context.channel().attr(Constants.LOCAL).get();
            if (CollectionUtils.isEmpty(map)) {
                return;
            }
            for (Map.Entry<String, Pair<EventLoopGroup, Channel>> entry : map.entrySet()) {
                if (entry.getValue() == null) {
                    continue;
                }
                if (entry.getValue().getRight() != null) {
                    try {
                        entry.getValue().getRight().close();
                    } catch (Exception ex) {
                        logger.error("", ex);
                    }
                }

                if (entry.getValue().getKey() != null) {
                    try {
                        entry.getValue().getKey().shutdownGracefully();
                    } catch (Exception ex) {
                        logger.error("", ex);
                    }
                }
            }
            context.channel().attr(Constants.LOCAL).set(new ConcurrentHashMap<>());
        } catch (Exception ex) {
            logger.error("", ex);
        }
    }

    public static void disConnectFromAgent(Channel proxy,Channel realChannel)
    {
        try {
            ConcurrentHashMap<String, Pair<EventLoopGroup, Channel>> localChannelMap = proxy.attr(Constants.LOCAL).get();
            if (CollectionUtils.isEmpty(localChannelMap)) {
                return;
            }

            Iterator<Map.Entry<String, Pair<EventLoopGroup, Channel>>> iterator = localChannelMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Pair<EventLoopGroup, Channel>> entry = iterator.next();
                Pair<EventLoopGroup, Channel> pair = entry.getValue();
                if (pair == null) {
                    // 删除
                    System.out.println("http移除空链接：" + entry.getKey());
                    iterator.remove();
                    continue;
                }

                if(pair.getRight().equals(realChannel))
                {
                    try {
                        if (pair.getKey() != null) {
                            pair.getKey().shutdownGracefully();
                        }
                        iterator.remove();
                        logger.info("http移除本次断开连接：" + entry.getKey());
                    }
                    catch (Exception ex)
                    {
                        logger.error("",ex);
                    }
                }
            }
        } catch (Exception ex) {
            logger.error("", ex);
        }
    }
}
